<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>仓管验收</h3>
    </div>
    <!-- 自定义下划线，替代el-divider -->
    <div class="custom-divider" />
    <!-- 搜索区域使用 transform 包裹 -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wapper">
        <div>
          <!-- <el-form
            ref="searchForm"
            :model="queryParams"
            :inline="true"
            label-width="90px"
          >
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                style="width: 350px"
                @change="handleDateChange"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="状态">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                clearable
                style="width: 150px"
                @change="handleStatusChange"
              >
                <el-option label="待验收" :value="0"></el-option>
                <el-option label="已验收" :value="1"></el-option>
                <el-option label="验收不通过" :value="-1"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form> -->
        </div>
      </el-card>
    </el-collapse-transition>

    <!-- 操作按钮区域 -->
    <div class="table-operations-wrapper">
      <div class="table-operations">
        <el-form
          ref="searchForm"
          :model="queryParams"
          :inline="true"
          label-width="90px"
        >
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              style="width: 350px"
              @change="handleDateChange"
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
              @change="handleStatusChange"
            >
              <el-option label="待验收" :value="0" />
              <el-option label="已验收" :value="1" />
              <el-option label="验收不通过" :value="-1" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
            >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            ></i>
          </el-button> -->
        <!-- <el-button size="small" type="success" @click="handleAdd">
            <i class="el-icon-plus"></i>
            新增
          </el-button>
          <el-button type="warning" size="small">
            <i class="el-icon-edit"></i>
            修改
          </el-button>
          <el-button type="danger" size="small">
            <i class="el-icon-delete"></i>
            批量删除
          </el-button> -->
      </div>

      <!-- 购物单录入区域 -->
      <div class="shopping-entry">
        <!-- <div class="entry-buttons">
          <el-button class="circle-btn" icon="el-icon-s-order">
            购货订单草稿
          </el-button>
          <el-button class="circle-btn" icon="el-icon-s-order">
            购货订单明细录入
          </el-button>
        </div> -->

        <!-- <div class="attachment-info">
            <el-link type="primary" class="upload-link">
              <i class="el-icon-paperclip"></i> 上传附件
            </el-link>
            <span class="order-number">单据编号: GHDD202503240001</span>
          </div> -->
      </div>
    </div>

    <!-- 商品表格区域 -->
    <el-table
      :data="acceptableList"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column> -->

      <el-table-column label="序号" type="index" width="60" align="center" />

      <el-table-column label="商品明细" width="900" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.list && scope.row.list.length > 0"
            class="goods-detail-container"
          >
            <!-- 循环渲染每个商品项 -->
            <div
              v-for="(item, index) in scope.row.list"
              :key="index"
              class="goods-item"
            >
              <div class="goods-row">
                <!-- 第一行：商品名称、仓库、数量、单价 -->
                <div class="goods-name">{{ item.goodsName }}</div>
                <div class="goods-type">{{ item.warehouseName }}</div>
                <div class="goods-number">
                  数量: <span class="number-value">{{ item.number }}</span>
                </div>
                <div class="goods-price">
                  单价: <span class="price-value">¥{{ item.unitPrice }}</span>
                </div>
                <div class="goods-tax-rate">
                  税率: <span class="tax-rate-value">{{ item.taxRate }}%</span>
                </div>
                <div class="goods-tax-price">
                  税额:
                  <span class="tax-price-value">¥{{ item.taxPrice }}</span>
                </div>
                <div class="goods-total">
                  总价: <span class="total-value">¥{{ item.totalPrice }}</span>
                </div>
                <div class="goods-tax-total">
                  含税:
                  <span class="tax-total-value">¥{{ item.totalTaxPrice }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-goods">暂无商品</div>
        </template>
      </el-table-column>

      <!-- <el-table-column
        prop="remark"
        label="备注"
        min-width="120"
        show-overflow-tooltip
      /> -->

      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="width" align="center">
        <template slot-scope="scope">
          <el-button
            type="warning"
            size="small"
            :disabled="scope.row.status === 1 || scope.row.status === 2"
            @click="handleCheck(scope.row)"
          >
            验收
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="queryParams.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: right"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 合计行 -->
    <!-- <div class="summary-row">
        <div class="summary-label">合计:</div>
        <div style="flex-grow: 1"></div>
        <div style="margin-right: 15px">数量: {{ totalQuantity }}</div>
      </div> -->

    <!-- 备注区域 -->
    <!-- <div class="remark-container" style="margin-top: 20px">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="备注信息"
          v-model="orderData.remark"
        >
        </el-input>
      </div> -->

    <!-- 金额信息区域 -->
    <!-- <div class="amount-container">
        <div class="amount-row">
          <div class="amount-item">
            <span class="amount-label">优惠率(%):</span>
            <el-input
              v-model="orderData.discountRate"
              class="amount-input"
            ></el-input>
          </div>

          <div class="amount-item">
            <span class="amount-label">优惠金额:</span>
            <el-input
              v-model="orderData.discountAmount"
              class="amount-input"
            ></el-input>
          </div>

          <div class="amount-item">
            <span class="amount-label">优惠后金额:</span>
            <el-input
              v-model="orderData.discountedAmount"
              class="amount-input"
              readonly
            ></el-input>
          </div>

          <div class="amount-item">
            <span class="amount-label">交货方式:</span>
            <el-select
              v-model="orderData.deliveryMethod"
              placeholder="请选择"
              class="amount-input wider"
            >
              <el-option
                v-for="item in deliveryMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </div> -->

    <!-- 底部工具栏 -->
    <!-- <div class="footer-toolbar">
        <div class="custom-field">
          <el-link type="primary" class="blue-text">
            <i class="el-icon-plus"></i> 自定义字段
          </el-link>
        </div>

        <div class="history-buttons">
          <el-button size="small" class="history-btn">历史单据</el-button>
          <el-button size="small" class="history-btn">操作日志</el-button>
        </div>
      </div> -->

    <!-- 分页组件 -->
    <!-- <el-row
        :gutter="10"
        style="margin-top: 20px"
        type="flex"
        justify="end"
        v-if="false"
      >
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-row> -->

    <!-- 新增 -->
    <el-dialog title="验收" :visible.sync="addDialogVisible" width="500px">
      <el-form ref="form" :model="addForm" :rules="rules" label-width="100px">
        <el-form-item label="仓管验收" prop="itemManage">
          <el-select
            v-model="addForm.itemManage"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in directorList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selCheckAcceptListApi,
  updateItemManageApi,
} from "@/api/check_and_accept";
import { selStaffListApi } from "@/api/system";
export default {
  name: "PurchaseDorder",
  data() {
    return {
      isFilterVisible: false, // 控制筛选区域显示/隐藏
      scanEnabled: false,
      orderData: {
        supplier: "",
        salesPerson: "",
        orderDate: "2025-03-24",
        deliveryDate: "2025-03-24",
        orderType: "purchase",
        deliveryAddress: "",
        remark: "",
        discountRate: "0",
        discountAmount: "0",
        discountedAmount: "0.00",
        deliveryMethod: "",
      },
      salesPersonOptions: [
        { value: "admin", label: "管理员" },
        { value: "zhangsan", label: "张三" },
        { value: "lisi", label: "李四" },
      ],
      addressOptions: [
        { value: "address1", label: "广州市天河区某某路123号" },
        { value: "address2", label: "深圳市南山区某某路456号" },
      ],
      deliveryMethodOptions: [
        { value: "express", label: "快递" },
        { value: "self", label: "自提" },
        { value: "delivery", label: "送货" },
      ],
      warehouseOptions: [
        { value: "warehouse1", label: "主仓库" },
        { value: "warehouse2", label: "次仓库" },
      ],
      tableData: [
        {
          id: 1,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
        {
          id: 2,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
        {
          id: 3,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
        {
          id: 4,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
        {
          id: 5,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
      ],
      totalQuantity: 0,
      multipleSelection: [],
      total: 0,
      // 新增
      addDialogVisible: false,
      // 新增验收
      addForm: {
        buyGoodsId: 0,
        id: 0,
        itemManage: "", // 仓管验收
        itemManageFile: "", // 验收文件
        operatorId: "", // 操作人
        remark: "", // 备注
      },
      acceptableList: [], // 可验收列表数据
      warehouseList: [
        { id: 1, name: "仓库1" },
        { id: 2, name: "仓库2" },
      ], // 仓库列表，实际应该从接口获取
      // 查询参数
      queryParams: {
        startTime: "", // 开始时间
        endTime: "", // 结束时间
        status: "", // 状态
        type: 2, // 固定为2，表示仓库管理列表
        page: 1, // 当前页码
        pageSize: 10, // 每页条数
      },
      // 职员列表
      staffQuery: {
        page: 1,
        pageSize: 10,
        name: "",
        mobile: "",
        parent: "",
      },
      directorList: [], // 主管列表
      // 状态选项
      statusOptions: [
        { value: 0, label: "待验收" },
        { value: 1, label: "已验收" },
      ],
      rules: {
        itemManage: [
          { required: true, message: "请选择仓管验收人员", trigger: "change" },
        ],
        remark: [
          { max: 200, message: "备注不能超过200个字符", trigger: "blur" },
        ],
      },
      dateRange: [],
    };
  },
  created() {
    this.getAcceptableList();
    this.selStaffList();
  },
  methods: {
    // 获取可发起验收列表
    async getAcceptableList() {
      try {
        const res = await selCheckAcceptListApi(this.queryParams);
        this.acceptableList = res.records;
        this.total = res.total;
      } catch (error) {
        console.error("获取列表失败:", error);
        this.$message.error("获取列表失败");
      }
    },
    // 新增
    handleAdd() {
      this.addDialogVisible = true;
    },
    // 职工列表
    async selStaffList() {
      const res = await selStaffListApi(this.staffQuery);
      this.directorList = res.records || [];
    },
    // 选择商品
    selectProduct(index, row) {
      this.$message({
        message: "选择商品，行索引：" + index,
        type: "info",
      });
    },

    // 计算总数量
    calculateTotal() {
      this.totalQuantity = this.tableData.reduce((sum, item) => {
        return sum + (Number(item.quantity) || 0);
      }, 0);
    },

    // 表格复选框选择
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 每页条数改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getAcceptableList();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getAcceptableList();
    },
    // 状态改变
    handleStatusChange() {
      this.queryParams.page = 1;
      this.getAcceptableList();
    },
    // 获取仓库名称
    getWarehouseName(warehouseId) {
      const warehouse = this.warehouseList.find(
        (item) => item.id === warehouseId
      );
      return warehouse ? warehouse.name : warehouseId;
    },

    // 格式化时间戳
    formatTime(timestamp) {
      if (!timestamp) return "";
      return new Date(timestamp).toLocaleString();
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: "warning", // 待验收
        1: "success", // 已验收
        2: "primary", // 验收不通过
      };
      return statusMap[status] || "info";
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: "待验收",
        1: "已验收",
        2: "已发起入库",
      };
      return statusMap[status] || "未知状态";
    },

    // 点击验收按钮
    handleCheck(row) {
      this.addForm = {
        buyGoodsId: row.goodsId,
        id: row.id,
        itemManage: "",
        itemManageFile: "",
        operatorId: "",
        remark: row.remark || "",
      };
      this.addDialogVisible = true;
    },

    // 提交验收
    async handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const res = await updateItemManageApi(this.addForm);
            if (res.code === 1) {
              this.$message.success("验收提交成功");
              this.addDialogVisible = false;
              this.getAcceptableList(); // 刷新列表
            } else {
              this.$message.error(res.msg || "验收提交失败");
            }
          } catch (error) {
            console.error("验收提交失败:", error);
            this.$message.error("验收提交失败");
          }
        } else {
          return false;
        }
      });
    },

    // 搜索
    handleSearch() {
      this.queryParams.page = 1;
      this.getAcceptableList();
    },

    // 重置
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.queryParams = {
        ...this.queryParams,
        startTime: "",
        endTime: "",
        status: "",
        page: 1,
        type: 2,
      };
      this.getAcceptableList();
    },

    // 日期改变
    handleDateChange(val) {
      if (val) {
        // 设置开始时间为当天的 00:00:00
        const startDate = new Date(val[0]);
        startDate.setHours(0, 0, 0, 0);
        this.queryParams.startTime = Math.floor(startDate.getTime() / 1000);

        // 设置结束时间为当天的 23:59:59
        const endDate = new Date(val[1]);
        endDate.setHours(23, 59, 59, 999);
        this.queryParams.endTime = Math.floor(endDate.getTime() / 1000);
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.search-wapper {
  margin-bottom: 15px;
}
.table-operations-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.table-operations {
  margin-bottom: 15px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.shopping-entry {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  align-items: center;
}

.entry-buttons {
  display: flex;
}

.circle-btn {
  margin-right: 10px;
  border-radius: 20px;
}

.attachment-info {
  display: flex;
  align-items: center;
}

.upload-link {
  margin-right: 15px;
}

.product-header {
  display: flex;
  align-items: center;
}

.required-mark {
  color: #f56c6c;
  margin-right: 4px;
}

.product-select {
  color: #409eff;
  cursor: pointer;
}

.product-image {
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
}

.batch-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.batch-tag {
  background-color: #909399;
  color: white;
  font-size: 10px;
  padding: 0 4px;
  border-radius: 2px;
}

.info-header {
  display: flex;
  align-items: center;
}

.info-header .el-icon-question {
  margin-left: 4px;
  color: #909399;
  cursor: help;
}

/* 合计行 */
.summary-row {
  display: flex;
  background-color: #fdf6ec;
  padding: 10px 15px;
  font-weight: bold;
  border: 1px solid #ebeef5;
  border-top: none;
}

.summary-label {
  width: 50px;
}

/* 备注区域 */
.remark-container {
  margin-bottom: 20px;
}

/* 自定义下划线 */
.custom-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 13px 0;
}

/* 金额信息区域 */
.amount-container {
  margin-bottom: 20px;
}

.amount-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.amount-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.amount-label {
  white-space: nowrap;
  margin-right: 5px;
  width: 80px;
  text-align: right;
}

.amount-input {
  width: 120px;
}

.amount-input.wider {
  width: 150px;
}

/* 底部工具栏 */
.footer-toolbar {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.blue-text {
  color: #409eff;
}

.history-buttons .history-btn {
  margin-left: 10px;
}

.blue-radio.el-radio ::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #409eff;
}

.address-edit {
  margin-left: 5px;
  cursor: pointer;
  color: #409eff;
}

.el-table .cell {
  text-align: center;
}

.el-tag {
  margin: 0 auto;
}

.operation-btn {
  color: #409eff;
}

/* 商品明细样式 */
.goods-detail-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  text-align: left;
  padding: 5px;
}

.goods-item {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
}

.goods-row {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.goods-row:last-child {
  margin-bottom: 0;
}

/* 第一行样式 */
.goods-name {
  width: 120px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 10px;
}

.goods-type {
  width: 120px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-number {
  width: 100px;
  color: #606266;

  .number-value {
    color: #409eff;
    font-weight: 500;
  }
}

.goods-price {
  width: 120px;
  color: #606266;

  .price-value {
    color: #67c23a;
    font-weight: 500;
  }
}

/* 第二行样式 */
.goods-tax-rate {
  width: 120px;
  color: #606266;
  padding-left: 10px;

  .tax-rate-value {
    color: #909399;
  }
}

.goods-tax-price {
  width: 120px;
  color: #606266;

  .tax-price-value {
    color: #e6a23c;
  }
}

.goods-total {
  width: 100px;
  color: #606266;

  .total-value {
    color: #f56c6c;
    font-weight: 500;
  }
}

.goods-tax-total {
  width: 120px;
  color: #606266;

  .tax-total-value {
    color: #f56c6c;
    font-weight: 500;
  }
}
</style>
